import React, { useEffect, useState } from 'react';
import { useHistory } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
import Grid from '@material-ui/core/Grid';
import {
  Button,
  Step,
  StepContent,
  StepLabel,
  Stepper,
  Tooltip,
  Typography,
} from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import Checkbox from '@material-ui/core/Checkbox';
import Paper from '@material-ui/core/Paper';
import { getBasicIndicatorPreviewList } from '../../../../../redux/reducers/compositeEditor';
import Visualize from "./Visualize/Visualize";
import VisualizationPreview from './VisualizationPreview/VisualizationPreview'
import {scrollToTop} from "../../../../../assets/functions/functions";
import ScrollMenu from "react-horizontal-scrolling-menu";

import { setActiveIndicatorStep,
  generateIndicatorPreview,
  getAllPlatforms,
  resetIndicatorSession,
  saveIndicatorPreview,
  getVisualizationMethodsAndTypes,
  setCompletedIndicatorStep,
  setGeneratedVisualizationCode } from '../../../../../redux/reducers/editor';

  import { generateCompositeIndicatorPreview,
    setGeneratedCompositeVisualizationCode
    } from '../../../../../redux/reducers/compositeEditor';
import {
  queryGeneratorWrapper,
  statementDurationWrapper,
} from '../../../../../ruleEngine/rulesGenerator';

import WbIncandescentIcon from '@material-ui/icons/WbIncandescent';
import Accordion from '@material-ui/core/Accordion';
import AccordionSummary from '@material-ui/core/AccordionSummary';
import AccordionDetails from '@material-ui/core/AccordionDetails';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import AddCircleIcon from '@material-ui/icons/AddCircle';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import RemoveRedEyeIcon from '@material-ui/icons/RemoveRedEye';
import TutorialSlides from '../../Common/TutorialSlides/TutorialSlides';
import { editorTutorialSteps } from '../../../../../assets/constants/data/data';
import HistoryIcon from '@material-ui/icons/History';
import { resetAllErrors } from '../../../../../redux/reducers/errorMessages';

import InsertChartIcon from '@material-ui/icons/InsertChart';
import Card from '@material-ui/core/Card';
import CardActionArea from '@material-ui/core/CardActionArea';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import useSyncCallback from '../../../../../redux/useSyncCallback';
import '../../../../../assets/css/compositeEditor/index.css';

const elemPrefix = "test";
const getId = (index) => `${elemPrefix}${index}`;

const getItems = () =>
  Array(20)
    .fill(0)
    .map((_, ind) => ({ id: getId(ind) }));

const useStyles = makeStyles((theme) => ({
  gutterTop: {
    marginTop: theme.spacing(2),
  },
  gutterBottom: {
    marginBottom: theme.spacing(2),
  },
  stepper: {
    backgroundColor:
      theme.palette.type === 'light' ? theme.palette.common.white : '#212121',
  },
  root: {
    margin: 'auto',
  },
  title:{
    padding:10,
    color:'green',
    fontSize: '20px',
    fontWeight: 700
  },
  titleError:{
    padding:10,
    color:'grey',
    fontSize: '20px',
    fontWeight: 700
  },
  outercard: {
    margin: 15,
    columnCount: 4,
    columnGap: '2em',
  },
  card: {
    maxWidth: 300,
    padding: '0px',
  },
  paper: {
    width: 400,
    height: 230,
    overflow: 'auto',
  },
  button: {
    margin: theme.spacing(0.5, 0),
  },
  actionsContainer: {
    marginBottom: theme.spacing(2),
  },
  resetContainer: {
    padding: theme.spacing(3),
  },
}));

function not(a, b) {
  return a.filter((value) => b.indexOf(value) === -1);
}

function intersection(a, b) {
  return a.filter((value) => b.indexOf(value) !== -1);
}

function CompositeIndicator() {
  const basicIndicatorPreviewMap = useSelector(
    (state) => state.compositeEditor.baiscIndicatorPreviewList
  )
  const basicIndicatorPreviewList = Object.values(useSelector(
    (state) => state.compositeEditor.baiscIndicatorPreviewList
  ));
  const activeStep = useSelector((state) => state.editor.common.activeStep);

  const classes = useStyles();
  const [checked, setChecked] = React.useState([]);
  const [left, setLeft] = React.useState([0, 1, 2, 3]);
  const [right, setRight] = React.useState([]);
  const [indicators, setIndicators] = useState(basicIndicatorPreviewList);
  const [selected, setSelected] = useState("");

  const leftChecked = intersection(checked, left);
  const rightChecked = intersection(checked, right);
  const history = useHistory();
  const dispatch = useDispatch();
  const styles = useStyles();
  const [feedback, setFeedback] = useState({
    showHelp: true,
    openMenu: true,
    openResetModal: false,
    openSaveProgressModal: false,
    openBackToEditorModal: false,
    openBackToDashboardModal: false,
    openSaveProgressErrorSnackbar: false,
  });
  const [selectedIndicators, setSelectedIndicators] = React.useState([]);
  const [selects, setSelects] = React.useState({});
  const [disables, setDisables] = React.useState({});
  const [currentIndicatorPreview, setCurrentIndicatorPreview] =
    React.useState({});
    const completedStep = useSelector((state) => state.editor.common.completedStep);
    const [movieCast, setMovieCast] = useState("");
    const openTutorial = useSelector((state) => state.commonSettings.basicIndicatorTutorialSkip);
    const selectedAnalysisMethod = useSelector(state => state.editor.selectedData.analysisMethod);
    const selectedVisualizationMethodsAndTypes = useSelector(state => state.editor.selectedData.visualizationMethodsAndTypes);
    const selectedVisualizationMapping = useSelector(state => state.editor.selectedData.mappingVizInputAnalysisOutput);
    const selectedPlatform = useSelector(state => state.editor.selectedData.platforms);
    const selectedActivityName = useSelector(state => state.editor.selectedData.activityName);
    const selectedActivityTypes = useSelector(state => state.editor.selectedData.activityTypes);
    const selectedActionOnActivities = useSelector(state => state.editor.selectedData.actionOnActivities);
    const selectedActivityExtensionData = useSelector(state => state.editor.selectedData.activityExtensionId);
    const selectedContextActivities = useSelector(state => state.editor.selectedData.contextActivities);
    const selectedResult = useSelector(state => state.editor.selectedData.result);
    const timeDurationData = useSelector(state => state.editor.selectedData.timeDuration);
    const selectedMappingAnalysisInputAttributesData = useSelector(state => state.editor.selectedData.mappingAnalysisInputAttributesData);
    const selectedAnalyticsMethodParams = useSelector(state => state.editor.selectedData.analysisMethodParams);
    const selectedVisualizationMethod = useSelector(state => state.editor.selectedData.visualizationMethod);
    const [analysisMethodOutputsData, setAnalysisMethodOutputsData] = React.useState({})
  const handleChange = (event) => {
    let indicatorId = event.target.name.split('@')[0];
    let methodId = event.target.name.split('@')[1];
    setSelects({ ...selects, [indicatorId]: event.target.checked });
    if (event.target.checked === true) {
      setSelectedIndicators([...selectedIndicators, indicatorId]);
      setCurrentIndicatorPreview(basicIndicatorPreviewMap[indicatorId]);

      console.log('!',basicIndicatorPreviewMap,indicatorId)
      const methodMapList = basicIndicatorPreviewMap[indicatorId]['indicators'][0]['methodToVisualizationConfig']['mapping']
      const _methodMapList = []
      for (let i in methodMapList){
        _methodMapList.push(methodMapList[i]['outputPort'])
      }
      setAnalysisMethodOutputsData(_methodMapList)
      let _disables = {};
      for (let i in basicIndicatorPreviewList) {
        if (
          basicIndicatorPreviewList[i]['id'] !== indicatorId &&
          basicIndicatorPreviewList[i]['analyticsMethodId'] !== methodId
        ) {
          _disables = {
            ..._disables,
            [basicIndicatorPreviewList[i]['id']]: true,
          };
        }
      }
      setDisables(_disables);
    } else {
      let i = selectedIndicators.indexOf(indicatorId);
      setCurrentIndicatorPreview({});
      setDisables({});
      if (i !== -1) {
        selectedIndicators.splice(i, 1);
      }
      setSelectedIndicators([...selectedIndicators]);
    }
    func();
  };
  const func = useSyncCallback(() => {
    console.log('selectedIndicators', selectedIndicators);
    console.log('currentPreviewIndicator', currentIndicatorPreview);
    console.log('disables', disables);
  });

  useEffect(() => {
    dispatch(getBasicIndicatorPreviewList());
    scrollToTop();
  }, []);

  const handleToggle = (value) => () => {
    const currentIndex = checked.indexOf(value);
    const newChecked = [...checked];

    if (currentIndex === -1) {
      newChecked.push(value);
    } else {
      newChecked.splice(currentIndex, 1);
    }

    setChecked(newChecked);
  };

  const handleAllRight = () => {
    setRight(right.concat(left));
    setLeft([]);
  };
  const handleStepForward = () => {
    dispatch(setActiveIndicatorStep(activeStep + 1));
  };
  const handleStepBackward = () => {
    dispatch(setActiveIndicatorStep(activeStep - 1));
  };
  const handleCheckedRight = () => {
    setRight(right.concat(leftChecked));
    setLeft(not(left, leftChecked));
    setChecked(not(checked, leftChecked));
  };

  const handleCheckedLeft = () => { 
    setLeft(left.concat(rightChecked));
    setRight(not(right, rightChecked));
    setChecked(not(checked, rightChecked));
  };
  const handleOpenVisualization = () => {
    dispatch(setGeneratedCompositeVisualizationCode("", ""))
    let queryBuilder = {
      platform: selectedPlatform,
      activityTypes: selectedActivityTypes,
      actionOnActivities: selectedActionOnActivities,
      activityName: selectedActivityName,
      result: selectedResult,
      contextActivities: selectedContextActivities,
      activityExtensionId: selectedActivityExtensionData
    };
    let parametersToBeReturnedInResult = {}
    selectedMappingAnalysisInputAttributesData.forEach(data => {
      parametersToBeReturnedInResult[data.outputPort.id] = 1
    })
    
    let methodInputParams = JSON.stringify(selectedAnalyticsMethodParams.reduce((obj, item) => {
      obj[item.id] = item.value.toString()
      return obj
    }, {}))
    let _queries={}
    let _queryToMethodConfig={}
    let _analyticsMethodId={}
    let _visualizationInputParams={}
    console.log('selectedIndicators',selectedIndicators)
    for(let index in Object.keys(basicIndicatorPreviewMap)){
      if (selectedIndicators.indexOf(Object.keys(basicIndicatorPreviewMap)[index])!==-1){
        _queries[`${Object.keys(_queries).length}`] = Object.values(basicIndicatorPreviewMap)[index]['indicators'][0]['query']['0']
        _queryToMethodConfig[`${Object.keys(_queryToMethodConfig).length}`] = Object.values(basicIndicatorPreviewMap)[index]['indicators'][0]['queryToMethodConfig']['0']
        _analyticsMethodId[`${Object.keys(_analyticsMethodId).length}`] = Object.values(basicIndicatorPreviewMap)[index]['analyticsMethodId']
        _visualizationInputParams[`${Object.keys(_visualizationInputParams).length}`] = ""
      }
    }
    console.log('_queries',_queries)
    let getCompositeIndicatorPreviewCode = {
      queries: _queries,
      indicatorType: "composite",
      analyticsMethodId: _analyticsMethodId,
      queryToMethodConfig: _queryToMethodConfig,
      methodInputParams: currentIndicatorPreview['indicators'][0]['methodInputParams']?currentIndicatorPreview['indicators'][0]['methodInputParams']:{"0":""},
      visualizationInputParams: _visualizationInputParams,
      additionalParams: {"rid": Date.now(),"width": 700, "height": 600},
      visualizationLibraryId: selectedVisualizationMethodsAndTypes[0].id,
      visualizationTypeId: selectedVisualizationMethodsAndTypes[0].vId,
      methodToVisualizationConfig: {mapping: selectedVisualizationMapping}
    }
    console.log('getCompositeIndicatorPreviewCode',getCompositeIndicatorPreviewCode)
    // console.log(JSON.stringify(getCompositeIndicatorPreviewCode));
    dispatch(generateCompositeIndicatorPreview(getCompositeIndicatorPreviewCode));
    dispatch(saveIndicatorPreview(getCompositeIndicatorPreviewCode));

  }

  // One item component
  // selected prop will be passed


  // All items component
  // Important! add unique key
  const Menu = (list, selected) =>
    list &&
    list.map((el) => {
      // return <MenuItem item={el} key={el.id} selected={selected} />;
      // return <div key={el.id} style={{width:200,height:100,backgroundColor:'red',margin:5}}><h1>{el.name}</h1></div>
      return                 <Card className={classes.card}>
      <CardActionArea>
        <CardContent>
          <div dangerouslySetInnerHTML={{__html:el['indicatorRequestCode']}}></div>
        </CardContent>
      </CardActionArea>
      <CardActions>
        <FormControlLabel
          control={
            <Checkbox
              checked={selects[el.id]}
              onChange={handleChange}
              disabled={disables[el.id]}
              name={`${el.id}@${el.analyticsMethodId}`}
              color="primary"
            />
          }
          
          label="Primary"
        />
      </CardActions>
    </Card>
    });

    const onSelect = (key) => {
      dispatch({ type: "SET_ACTOR_ID", value: key });
      // console.log(history.push);
      // history.push(`/${key}`);
      setSelected(key);
      console.log(key);
  
      //this.setState({ selected: key })
    };
  
    const Arrow = ({ text, className }) => {
      return <div className={className}>{text}</div>;
    };
    const ArrowLeft = Arrow({ text: "", className: "arrow-prev" });
    const ArrowRight = Arrow({ text: "", className: "arrow-next" });
  
    // const menuItems = Menu(movieCast.cast, selected);
    const menuItems = Menu(basicIndicatorPreviewList, selected);
    console.log('menuItems',menuItems)
  const handleAllLeft = () => {
    setLeft(left.concat(right));
    setRight([]);
  };
  const handleComplete = () => {
    const newCompleted = completedStep;
    newCompleted[activeStep] = true;
    dispatch(setCompletedIndicatorStep(newCompleted));
  };
  const handleFeedback = (name, value) => {
    setFeedback(() => ({
      ...feedback,
      [name]: !value,
    }));
  };
  const customList = (items) => (
    <Paper className={classes.paper}>
      <List dense component="div" role="list">
        {items.map((value) => {
          const labelId = `transfer-list-item-${value}-label`;

          return (
            <ListItem
              key={value}
              role="listitem"
              button
              onClick={handleToggle(value)}
            >
              <ListItemIcon>
                <Checkbox
                  checked={checked.indexOf(value) !== -1}
                  tabIndex={-1}
                  disableRipple
                  inputProps={{ 'aria-labelledby': labelId }}
                />
              </ListItemIcon>
              <ListItemText
                id={labelId}
                primary={`Basic Indicator ${value + 1}`}
              />
              <InsertChartIcon />
            </ListItem>
          );
        })}
        <ListItem />
      </List>
    </Paper>
  );
  const continueToVisualizations = () => {
    dispatch(getVisualizationMethodsAndTypes());
    handleStepForward()
  }
  const steps = [
    {
      name: 'Select Indicator',
      component: (
        <div>
          <div className={classes.outercard}>
            {basicIndicatorPreviewList.map((item) => (
              <>
                <Card className={classes.card}>
                  <CardActionArea>
                    <CardContent>
                     <div dangerouslySetInnerHTML={{__html:item['indicatorRequestCode']}}></div>
                    </CardContent>
                  </CardActionArea>
                  <CardActions>
                    <FormControlLabel
                      control={
                        <Checkbox
                          checked={selects[item.id]}
                          onChange={handleChange}
                          disabled={disables[item.id]}
                          name={`${item.id}@${item.analyticsMethodId}`}
                          color="primary"
                        />
                      }
                      label="Primary"
                    />
                  </CardActions>
                </Card>
              </>
            ))}
          </div>

{Object.keys(currentIndicatorPreview).length!==0?
<>
<Card className="cast-div" variant="outlined">
          <Typography className={classes.title} color="textSecondary" gutterBottom>
          Avaliable Basic Indicator
        </Typography>
          {basicIndicatorPreviewList && (
            <ScrollMenu
              data={menuItems}
              arrowLeft={ArrowLeft}
              arrowRight={ArrowRight}
              selected={selected}
              onSelect={onSelect}
            />
          )}
        </Card>
        <hr/>
        
        <Card className="cast-div">
        <Typography className={classes.titleError} color="textSecondary" gutterBottom>
      <Tooltip title="Why?" placement="right-end">
              <Button>Unavailable Basic Indicator</Button>
            </Tooltip>
        </Typography>
          {basicIndicatorPreviewList && (
            <ScrollMenu
              data={menuItems}
              arrowLeft={ArrowLeft}
              arrowRight={ArrowRight}
              selected={selected}
              onSelect={onSelect}
            />
          )}
        </Card>
        </>
:<></>}
          
        
          <Button
            variant="contained"
            color="primary"
            onClick={continueToVisualizations}
            disabled={!(Object.keys(currentIndicatorPreview).length !== 0)}
          >
            Next
          </Button>
        </div>
      ),
    },
    {
      name: 'Select Visualization',
      component: (
<Visualize classes={classes}
                            handleOpenVisualization={handleOpenVisualization}
                            handleStepForward={handleStepForward}
                            handleStepBackward={handleStepBackward}
                            analysisMethodOutputsData={analysisMethodOutputsData}
                            handleComplete={handleComplete}/>
      ),
    },
    {
      name: 'Preview',
      component: (
        <VisualizationPreview classes={classes} handleStepBackward={handleStepBackward}/>
      ),
    },
  ];

  return (
    <>
      <Grid container direction="column" className={classes.root}>
        <Grid
          container
          justify="space-between"
          lg={9}
          className={classes.gutterBottom}
        >
          <Tooltip placement="down" title={'Go back to the GQI Editor'}>
            <Button
              onClick={() => history.push('/editor')}
              startIcon={<ArrowBackIcon />}
            >
              Back
            </Button>
          </Tooltip>

          <Tooltip
            placement="down"
            title="All the selections done in the Basic indicator will be reset"
          >
            <Button
              startIcon={<HistoryIcon />}
              color="secondary"
              onClick={() =>
                handleFeedback('openResetModal', feedback.openResetModal)
              }
            >
              Reset
            </Button>
          </Tooltip>
        </Grid>

        <Typography variant="h3" className={styles.gutterBottom}>
          {' '}
          Composite Indicator{' '}
        </Typography>

        <Grid container justify="space-between" alignItems="center" lg={9}>
          <Grid item xs>
            <Typography variant="body1">
              Select the basic Indicator that uses the same Analytics Method,
              and then select the appropriate Visualization Method.
            </Typography>
          </Grid>
        </Grid>

        <Stepper
          activeStep={activeStep}
          orientation="vertical"
          className={classes.stepper}
        >
          {steps.map((step, index) => {
            return (
              <Step key={index}>
                <StepLabel>
                  <Typography variant="h5"> {step.name} </Typography>
                </StepLabel>
                <StepContent>{step.component}</StepContent>
              </Step>
            );
          })}
        </Stepper>
      </Grid>
    </>
  );
}

export default CompositeIndicator;
